package com.itheima.exception;


import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;



@RestControllerAdvice
@Slf4j
public class MyHandlerException {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RuntimeException.class)
    public Result handlerRuntimeException(RuntimeException ex){
        log.debug("error:"+ex);
        if(ex instanceof AccessDeniedException){
            return new Result(false,"未登录或权限不足,请联系管理员");
        }
        return new Result(false, MessageConst.ACTION_FAIL);
    }

    @ExceptionHandler({
            ServletException.class,
            HttpMessageConversionException.class,
            MethodArgumentNotValidException.class,
            MethodArgumentTypeMismatchException.class
    })
    public Exception handlerOtherException(Exception e){
        log.debug("出错了!!");
        return e;
    }


    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({
            Exception.class
    })
    public Result handlerException(Exception e) throws Exception {
        log.debug("error：" +e );
        return new Result(false, MessageConst.ACTION_FAIL);
    }
}
